package top.kpromise.fastdev.goods.service;

import org.springframework.stereotype.Service;
import top.kpromise.fastdev.goods.data.Config;
import top.kpromise.fastdev.goods.mapper.goods.IGoodsMapper;
import top.kpromise.fastdev.goods.mapper.image.IImageMapper;
import top.kpromise.fastdev.goods.mapper.generated.GoodsMapper;
import top.kpromise.fastdev.goods.model.request.CreateGoodsModel;
import top.kpromise.fastdev.goods.model.sql.Goods;
import top.kpromise.fastdev.goods.model.sql.Image;
import top.kpromise.fastdev.goods.utils.DateUtils;
import top.kpromise.fastdev.goods.utils.SnowflakeIdWorker;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
public class GoodsService {

    private final GoodsMapper goodsMapper;
    private final IGoodsMapper iGoodsMapper;
    private final IImageMapper iImageMapper;

    public GoodsService(GoodsMapper goodsMapper, IImageMapper iImageMapper, IGoodsMapper iGoodsMapper) {
        this.goodsMapper = goodsMapper;
        this.iImageMapper = iImageMapper;
        this.iGoodsMapper = iGoodsMapper;
    }

    public void createGoods(CreateGoodsModel createGoodsModel) {
        ArrayList<Image> banners = createGoodsModel.getBanners();
        if (banners == null || banners.isEmpty()) return;
        String goodsId = SnowflakeIdWorker.generateId();
        Goods goods = createGoodsModel.getGoodsDetail();
        goods.setGoodsId(goodsId);
        goods.setEnabled(0);
        goods.setOnSale(0);
        goods.setImage(banners.get(0).getUrl());
        goods.setCreatedAt(DateUtils.currentDate());
        goods.setUpdateAt(DateUtils.currentDate());
        goodsMapper.insert(goods);
        for (Image image : banners) {
            image.setRefId(goodsId);
            image.setType(Config.ImageType.GOODS_BANNER);
        }
        iImageMapper.insertForeach(banners);
    }

    public Map<String, Object> search(String title, int pageNo, int pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("list", iGoodsMapper.search(title, (pageNo - 1) * pageSize, pageSize));
        map.put("count", iGoodsMapper.searchCount(title, (pageNo - 1) * pageSize, pageSize));
        return map;
    }
}
